<template>
  <div class="quotation-list">
    <div class="tabs">
      <a-tabs type="card" v-model="quotationTimeType" @change="tabsChange">
        <a-tab-pane :key="1" tab="当前报价"> </a-tab-pane>
        <a-tab-pane :key="2" tab="历史报价"> </a-tab-pane>
        <c-button type="primary" slot="tabBarExtraContent" @click="goToIssue">
          发布报价
        </c-button>
      </a-tabs>
    </div>
    <div class="layout-content">
      <Filtrate @changeClass="changeClass" @changeStatus="changeStatus" />
    </div>
    <div class="layout-content">
      <c-table
        ref="table"
        :loading="loading"
        :data="data.pageData"
        :total="data.total"
        :columns="columns"
        expanded
        search
        searchPlaceholder="可输入规格、仓库进行搜索"
        @onSearch="onSearch"
        @expanded="getDetail"
        @pageChange="pageChange"
        @onReload="reload"
      >
        <!-- <template v-slot:header-r>
          <c-search-box
            v-model="searchKey"
            placeholder="可输入规格、仓库进行搜索"
            @search="reload"
          />
        </template> -->
        <template v-slot:amountAvailableTotalTitle>
          <span>剩余库存 </span>
          <a-tooltip placement="top" :mouseEnterDelay="0.5">
            <template slot="title">
              <span>刷新剩余库存</span>
            </template>
            <a-icon
              type="reload"
              class="cursor-pointer primary"
              @click="getQuotationIds"
              v-if="data.pageData && data.pageData.length !== 0"
            />
          </a-tooltip>
        </template>
        <template v-slot:amountAvailableTotal="{ row }">
          <span>{{ amountAvailableTotal(row) }}</span>
        </template>
        <template v-slot:quotationType="{ row }">
          <TagsStatus :flag="row" />
        </template>
        <template v-slot:expirationDate="{ row }">
          <!-- <c-tags
            :data="[{ label: $getTime(row.expirationDate), color: 'orange' }]"
          ></c-tags> -->
          {{ $getTime(row.expirationDate) }}
        </template>
        <template v-slot:priceType="{ row }">
          <TagsPriceType :flag="row" />
        </template>
        <template slot="expanded" slot-scope="{ row }">
          <!-- 判断id是为了避免多个QuotationDetail之间相互影响 -->
          <!-- quotationData改变时才会触发重新请求详情 -->
          <QuotationDetail
            ref="quotationDetail"
            type="1"
            :quotationData="quotationData"
            v-if="row.id === quotationData.id"
          />
        </template>
        <div class="handle" slot="handle" slot-scope="{ row }">
          <a-dropdown v-if="setBtns(row).length !== 0">
            <a-menu slot="overlay">
              <a-menu-item
                v-for="item in setBtns(row)"
                :key="item.flag"
                @click="clickEvent(item.clickEvent, row)"
              >
                {{ item.name }}
              </a-menu-item>
            </a-menu>
            <a-button size="small">操作 <a-icon type="down"/></a-button>
          </a-dropdown>
        </div>
      </c-table>
    </div>
    <c-modal
      title="调整库存"
      v-model="updateStockVisible"
      :width="900"
      @ok="updateStock"
      @cancel="$refs.stock.resetData()"
    >
      <Stock
        ref="stock"
        :quotationData="updateRow"
        @success="updateStockSuccess"
      />
    </c-modal>
    <c-modal
      :title="updatePremiumTitle"
      v-model="updatePremiumVisible"
      :width="900"
      @ok="updatePremium"
      @cancel="$refs.premium.resetData()"
    >
      <Premium
        ref="premium"
        :quotationData="updateRow"
        @success="updatePremiumSuccess"
      />
    </c-modal>
  </div>
</template>

<script>
import Filtrate from "./components/filtrate";
import {
  getMyQuotation,
  delMyQuotation,
  ontheshelve,
  auditQuotation,
  offtheshelve,
  getamountavailabletotalbyids,
  exportquotationresiduals
} from "@/api/quotation";
import { mapState } from "vuex";
import TagsStatus from "@/components-business/quotation/status";
import TagsPriceType from "@/components-business/quotation/priceType";
import Stock from "./components/stock";
import Premium from "./components/premium";
import QuotationDetail from "../components/quotationDetail";
import btnJudge from "./btnJudge.js";
import { downloadFile } from "@/util/common";

const columns = [
  {
    title: "商品种类",
    dataIndex: "categoryName"
  },
  {
    title: "发布人",
    dataIndex: "createUsername"
  },
  {
    title: "总库存",
    dataIndex: "amountTotal"
  },
  {
    slots: { title: "amountAvailableTotalTitle" },
    scopedSlots: { customRender: "amountAvailableTotal" }
  },
  {
    title: "作价方式",
    scopedSlots: { customRender: "priceType" }
  },
  {
    title: "适用合约月",
    dataIndex: "futuresContract"
  },
  {
    title: "状态",
    dataIndex: "quotationType",
    scopedSlots: { customRender: "quotationType" }
  },
  {
    title: "截止时间",
    scopedSlots: { customRender: "expirationDate" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "handle" }
  }
];

const btns = [
  {
    name: "同意",
    clickEvent: "agree",
    flag: "agree"
  },
  {
    name: "拒绝",
    clickEvent: "reject",
    flag: "reject"
  },
  {
    name: "上架",
    clickEvent: "added",
    flag: "added"
  },
  {
    name: "下架",
    clickEvent: "unshelve",
    flag: "unshelve"
  },
  {
    name: "编辑",
    clickEvent: "edit",
    flag: "edit"
  },
  {
    name: "删除",
    clickEvent: "del",
    flag: "del"
  },
  {
    name: "调整库存",
    clickEvent: "showUpdateStock",
    flag: "updateStock"
  },
  {
    name: "调整升贴水",
    clickEvent: "showUpdatePremium",
    flag: "updatePremium"
  },
  {
    name: "调整价格",
    clickEvent: "showUpdatePrice",
    flag: "updatePrice"
  },
  {
    name: "导出剩余数",
    clickEvent: "updateResidue",
    flag: "residue"
  }
];

export default {
  components: {
    Filtrate,
    TagsStatus,
    TagsPriceType,
    Stock,
    Premium,
    QuotationDetail
  },
  data() {
    return {
      quotationTimeType: 1, // 1当前报价 2历史报价
      data: {}, // 主table数据
      columns, // 主table列
      loading: false, // 主table加载
      detailLoading: false, // 详情table加载
      searchKey: undefined, // 搜索关键词
      pageNum: 1,
      updateStockVisible: false, // 批量调整库存
      updatePremiumVisible: false, // 批量调整升贴水
      updatePremiumTitle: undefined,
      categoryType: undefined, // 商品类别（1:有色，2:黑色，3:化工，4:农产品，5:能源，6:其他,全部则不传）
      quotationType: undefined, // 报价状态（0:待审核，1:在售中，2:已售完，3:已下架，4:已拒绝，全部则不传）
      updateRow: {}, // 调整的row信息
      isExpanded: false, // 是否有已展开行
      quotationData: {}
    };
  },
  computed: {
    ...mapState(["user"]),
    // 设置可操作的按钮
    setBtns() {
      return row => {
        let res = [];
        btns.forEach(item => {
          // 判断是否拥有对应权限、对应的报价状态、是否管理员、当前用户是否发布人
          if (this.$btn(item.flag)) {
            if (this.btnJudge(item.flag, row)) {
              res.push(item);
            }
          }
        });
        // console.log(res)
        return res;
      };
    },
    // 实时计算剩余库存，解决更新table数据后视图没有更新，避免使用$set更新table带来的问题，比如展开行自动收起，因为整个table重新渲染了
    amountAvailableTotal() {
      return row => {
        let res;
        this.data.pageData.forEach(item => {
          if (item.id === row.id) res = item.amountAvailableTotal;
        });
        return res;
      };
    }
  },
  watch: {
    pageNum() {
      this.getMyQuotations();
    }
  },
  methods: {
    // 搜索
    onSearch(val) {
      this.searchKey = val;
      this.reload();
    },
    // 调整库存后回调
    updateStockSuccess() {
      this.updateStockVisible = false;
      this.getMyQuotations();
      if (this.isExpanded) this.$refs.quotationDetail.getQuotationDetail();
    },
    // 调整升贴水/价格回调
    updatePremiumSuccess() {
      this.updatePremiumVisible = false;
      this.getMyQuotations();
      if (this.isExpanded) this.$refs.quotationDetail.getQuotationDetail();
    },
    // 点击刷新剩余库存按钮, 获取所有报价id，用于查询剩余库存
    getQuotationIds() {
      // 没有数据时禁用
      let ids = this.data.pageData.map(i => i.id);
      this.getAmountAvailableTotal(ids);
    },
    // 查询剩余库存
    getAmountAvailableTotal(data) {
      this.loading = true;
      getamountavailabletotalbyids({
        quotationIds: data
      })
        .then(res => {
          this.updateAmountAvailableTotal(res);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 更新table剩余库存
    updateAmountAvailableTotal(data) {
      this.data.pageData.forEach(item => {
        data.forEach(i => {
          if (item.id === i.id) {
            item.amountAvailableTotal = i.amountAvailableTotal;
          }
        });
      });
    },
    // 选择分类
    changeClass(val) {
      this.categoryType = val.id === "all" ? undefined : val.id;
      this.$refs.table.setPage(1);
      this.reload();
    },
    // 选择状态
    changeStatus(val) {
      this.quotationType = val.value === "all" ? undefined : val.value;
      this.$refs.table.setPage(1);
      this.reload();
    },
    clickEvent(clickEvent, row) {
      this[clickEvent](row);
    },
    // 编辑报价
    edit(row) {
      this.$router.push({
        name: "quotationUpdate",
        params: {
          quotationDetail: { quotationId: row.id, version: row.version }
        }
      });
    },
    // 删除报价
    del(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: "是否确认将该报价的所有商品批量删除？",
        onOk() {
          return new Promise((resolve, reject) => {
            delMyQuotation({
              quotationId: row.id,
              version: row.version
            })
              .then(() => {
                resolve();
                _this.$message.success("操作成功");
                _this.reload();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 同意
    agree(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: "是否确认同意该报价审核或上架操作？",
        onOk() {
          return new Promise((resolve, reject) => {
            auditQuotation({
              quotationId: row.id,
              auditState: 1,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 拒绝报价
    reject(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: "是否确认拒绝该报价审核？",
        onOk() {
          return new Promise((resolve, reject) => {
            auditQuotation({
              quotationId: row.id,
              auditState: 2,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 调整库存
    showUpdateStock(row) {
      this.updateStockVisible = true;
      this.updateRow = row;
      this.$nextTick(() => {
        this.$refs.stock.getQuotationDetail();
      });
    },
    // 提交调整库存
    updateStock() {
      this.$refs.stock.submit();
    },
    // 调整升贴水
    showUpdatePremium(row) {
      this.updatePremiumTitle = "调整升贴水";
      this.updatePremiumVisible = true;
      this.updateRow = row;
      this.$nextTick(() => {
        this.$refs.premium.getQuotationDetail();
      });
    },
    // 调整价格
    showUpdatePrice(row) {
      this.updatePremiumTitle = "调整价格";
      this.updatePremiumVisible = true;
      this.updateRow = row;
      this.$nextTick(() => {
        this.$refs.premium.getQuotationDetail();
      });
    },
    // 提交调整升贴水
    updatePremium() {
      this.$refs.premium.submitVerify();
    },
    // 上架
    added(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: "是否确认将该报价的所有商品批量上架？",
        onOk() {
          return new Promise((resolve, reject) => {
            ontheshelve({
              quotationId: row.id,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 下架
    unshelve(row) {
      let _this = this;
      this.$confirm({
        title: "温馨提示",
        content: "是否确认将该报价的所有商品批量下架？",
        onOk() {
          return new Promise((resolve, reject) => {
            offtheshelve({
              quotationId: row.id,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        }
      });
    },
    // 按钮根据业务逻辑判断显隐
    btnJudge(flag, row) {
      let res = btnJudge(flag, row);
      return res;
    },
    reload() {
      this.pageNum = 1;
      this.getMyQuotations();
    },
    // 设置标签
    setTag(label) {
      return [{ label: label, color: "blue" }];
    },
    tabsChange() {
      this.reload();
    },
    // 前往发布报价
    goToIssue() {
      this.$router.push({ name: "quotationIssue" });
    },
    // 获取报价列表
    getMyQuotations() {
      this.loading = true;
      getMyQuotation({
        searchKey: this.searchKey,
        categoryType: this.categoryType,
        quotationType: this.quotationType,
        quotationTimeType: this.quotationTimeType,
        pageData: {
          pageNum: this.pageNum,
          pageSize: 20
        }
      })
        .then(res => {
          this.data = res;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取报价详情
    getDetail(row) {
      this.isExpanded = row.expanded;
      if (row.expanded) {
        this.quotationData = row.record;
      }
    },
    // 分页触发
    pageChange(pagination) {
      this.pageNum = pagination;
    },
    // 导出剩余数
    updateResidue(row) {
      exportquotationresiduals({
        quotationId: row.id
      }).then(res => {
        downloadFile(res);
      });
    }
  },
  created() {
    this.getMyQuotations();
  }
};
</script>

<style lang="scss" scoped>
.tabs {
  ::v-deep .ant-tabs-bar {
    margin-bottom: 0;
  }
  ::v-deep .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab {
    border-left: 0;
    border-top: 0;
    border-right: 0;
  }
}
</style>
